<template>
    <div>

        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-button type="primary" @click="showAddEditorRole = true">添加角色</el-button>
            <!-- 列表区域 -->
            <el-table :data="roleList" :border="true" stripe>
                <el-table-column type="expand">
                    <template v-slot="scope">
                        <el-row :class="['bdbuttom', index === 0 ? 'bdtop' : '', 'vcenter']"
                            v-for="(item, index) in scope.row.children" :key="item.id">
                            <!-- 一级权限菜单 -->
                            <el-col :span="5">
                                <el-tag closable>{{ item.authName }}</el-tag>
                                <i @click="removeRightById(scope.row, item3.id)" class=" el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级三级权限菜单 -->
                            <el-col :span="19">
                                <!-- 通过for循环渲染二级菜单 -->
                                <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                                    v-for="(item2, index2) in item.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @click="removeRightById(scope.row, item2.id)">{{
                                            item2.authName }}</el-tag>
                                        <i class=" el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!-- 通过for循环渲染三季菜单 -->
                                        <el-tag :closable="true" v-for="item3 in item2.children" :key="item3.id"
                                            type="warning" @click="removeRightById(scope.row, item3.id)">{{
                                                item3.authName }}</el-tag>

                                    </el-col>
                                </el-row>

                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column type="角色名称" prop="roleName"></el-table-column>
                <el-table-column type="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column type="操作">
                    <template v-slot="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit"
                            @click="Editorrole(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete"
                            @click="removeEditRole(scope.row.id)">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting"
                            @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="showAddEditorRole" width="50%">
            <!-- from表单 -->
            <el-form :model="roleFormAdd" :rules="roleFormRules" ref="roleFormAddRef" label-width="70px">
                <el-form-item label="角色id">
                    <el-input v-model="roleFormAdd.roleId"></el-input>
                </el-form-item>
                <el-form-item label="角色名称">
                    <el-input v-model="roleFormAdd.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="roleFormAdd.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showAddEditorRole = false">取 消</el-button>
                <el-button type="primary" @click="addEditRole()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
            <!-- 树形控件 -->
            <el-tree node-key="id" :default-expand-all="true" :data="rightList" :props="treeProps" show-checkbox
                :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog title="角色编辑" :visible.sync="showEditorRole" width="50%">
            <!-- from表单 -->
            <el-form :model="roleForm" :rules="roleFormRules" ref="roleFormRef" label-width="70px">
                <el-form-item label="角色id">
                    <el-input v-model="roleForm.roleId" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色名称">
                    <el-input v-model="roleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="roleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showEditorRole = false">取 消</el-button>
                <el-button type="primary" @click="Modifyrole()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            //树桩显示权限
            roleList: [],
            //显示分配权限对话框
            setRightDialogVisible: false,
            //列表显示权限
            rightList: [],
            //树形控件的属性绑定
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            //默认选中的节点Id值数组
            defKeys: [],
            //添加角色的表单的数据绑定对象
            roleFormAdd: {},
            //当前即将分配角色的id
            roleId: '',
            //角色编辑的表单的数据绑定对象
            roleForm: {},
            //角色编辑的表单的验证规则对象
            roleFormRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            },
            //控制角色编辑对话框的显示和隐藏
            showEditorRole: false,
            //控制添加角色对话框的显示和隐藏
            showAddEditorRole: false,

        }
    },
    created() {
        this.getRoleList()
    },
    methods: {
        async getRoleList() {
            //它的意思是从 Promise 返回的对象中提取 data 属性，并将其赋值给本地变量 res。
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
            this.roleList = res.data
            this.$message.success('获取角色列表成功')
        },
        async removeRightById(role, rightId) {

            const confirmResult = await this.$confirm('确定要删除该权限吗?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmResult !== 'confirm') {
                return this.$message.error('取消了删除')
            }
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            if (res.meta.status !== 200) return this.$message.error('删除权限失败')

            role.children = res.data
            // this.getRoleList()
        },
        //展示分配权限的对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            //获取所有的数据
            const { data: res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
            this.rightList = res.data
            //递归获取三级节点的Id
            this.getLeafKeys(role, this.defKeys)
            // this.allotRights()
            this.setRightDialogVisible = true
        },
        //点击确定为角色分配权限
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            console.log(keys);
            const idStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
            if (res.meta.status !== 200) return this.$message.error('获取失败++++')
            this.getRoleList()
            this.setRightDialogVisible = false
            this.$message.success('获取成功')
        },
        //通过递归的形式,获取角色下所有的三级权限的id,并保存到 defKeys 数组中
        getLeafKeys(node, arr) {
            if (!node.children) return arr.push(node.id)
            node.children.forEach(item =>
                this.getLeafKeys(item, arr)
            )
        },
        //点击清除之前所选中的权限
        setRightDialogClose() {
            this.defKeys = []
        },

        //编辑角色
        async Editorrole(role) {
            const { data: res } = await this.$http.get('roles/' + role.id)
            if (res.meta.status !== 200) return this.$message.error('获取失败')
            this.roleForm = res.data
            console.log(this.roleForm);
            this.showEditorRole = true
        },
        //确定编辑角色按钮事件
        Modifyrole() {
            this.$refs.roleFormRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.put(`roles/${this.roleForm.roleId}`,
                    {
                        roleName: this.roleForm.roleName,
                        roleDesc: this.roleForm.roleDesc
                    }
                )
                if (res.meta.status !== 200) return this.$message.error('修改失败')
                this.$message.success('编辑角色成功')
                this.getRoleList()
                this.showEditorRole = false
            })
        },
        //删除角色事件
        async removeEditRole(id) {
            const confirmRole = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmRole !== 'confirm') return this.$message.error('已取消操作')
            const { data: res } = await this.$http.delete('roles/' + id)
            if (res.meta.status !== 200) return this.$message.error('删除角色失败')
            this.$message.success('删除角色成功')
            this.getRoleList()
        },
        //添加角色
        addEditRole() {
            this.$refs.roleFormAddRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post(`roles`,
                    {
                        roleId: this.roleFormAdd.roleId,
                        roleName: this.roleFormAdd.roleName,
                        roleDesc: this.roleFormAdd.roleDesc
                    }
                )
                if (res.meta.status !== 201) return this.$message.error('添加角色失败')
                this.$message.success('添加角色成功')
                this.getRoleList()
                this.showAddEditorRole = false
            })
        }
    }
}
</script>
<style lang="less" scoped>
.el-tag {
    margin: 15px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbuttom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>